package org.nvm.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LemmaTree {

	private LemmaNode root = null;
	
	private Map<Integer, List<LemmaNode>> childrenNodeMap = null;
	
	private int endIndex = 0;
	
	private int maxSize = 0;
	
	public LemmaTree() {
		root = new LemmaNode(new Lemma(0, 0, ""));
		childrenNodeMap = new HashMap<>();
		insertLemmaNode(root);
	}
	
	public void insertLemma(Lemma l) {
		maxSize ++;
		int pkey = l.getBegin();
		List<LemmaNode> parents = childrenNodeMap.get(pkey);//插入的节点
		if(parents != null) {
			for(LemmaNode ln : parents) {
				LemmaNode newNode = new LemmaNode(l);
				ln.addSub(newNode);
				newNode.setParent(ln);
				insertLemmaNode(newNode);
			}
		}
	}
	
	private void insertLemmaNode(LemmaNode ln) {
		int nodeKey = ln.getNodeKey();
		if(nodeKey > endIndex) {
			endIndex = nodeKey;
		}
		List<LemmaNode> list = childrenNodeMap.get(nodeKey);
		if(list == null) {
			list = new ArrayList<>(2);
			list.add(ln);
			childrenNodeMap.put(nodeKey, list);
		} else {
			list.add(ln);
		}
	}
	
	public LemmaPath bestPath() {
		List<LemmaNode> endNodes = childrenNodeMap.get(endIndex);
		LemmaPath result = null;
		double score = -100;
		if(endNodes != null) {
			for(LemmaNode node : endNodes) {
				List<Lemma> path = new ArrayList<>(maxSize);
				while(node != null && node.getNodeKey() > 0) {
					path.add(node.getData());
					node = node.getParent();
				}
				Collections.reverse(path);
				LemmaPath lemmaPath = new LemmaPath(path);
				double currentScore = lemmaPath.caculate();
				System.out.println(path + " : " + currentScore);
				if(currentScore > score) {
					score = currentScore;
					result = lemmaPath;
				}
				
			}
		}
		return result;
	}
}
